import { useEffect, useState } from "react";
import Header from "@/components/Header";
import {
  Input,
  Select,
  Table,
  Button,
  Spin,
  Modal,
  TableColumnsType,
  Form,
  TimePicker,
  Cascader,
  InputNumber,
  Tag,
  message,
  Popconfirm,
} from "antd";
import { DataType, Option, FormData } from "./interface/interfaces";

import "./css/store.scss";
import axios from "axios";
import moment from "moment";
const { Search } = Input;
import Map from "./map/index";
import Maps from "./setMap/Index";
import MapTwo from "./setMap/MapTwo";

//过滤
const filterOption = (
  input: string,
  option?: { label: string; value: string }
) => (option?.label ?? "").toLowerCase().includes(input.toLowerCase());

const options: Option[] = [
  {
    value: "北京市",
    label: "北京市",
    children: [
      {
        value: "天安门",
        label: "天安门",
      },
    ],
  },
  {
    value: "江苏省",
    label: "江苏省",
    children: [
      {
        value: "南京市",
        label: "南京市",
        children: [
          {
            value: "中华门",
            label: "中华门",
          },
        ],
      },
      {
        value: "苏州市",
        label: "苏州市",
        children: [
          {
            value: "姑苏区",
            label: "姑苏区",
          },
          {
            value: "虎丘区",
            label: "虎丘区",
          },
          {
            value: "吴江区",
            label: "吴江区",
          },
        ],
      },
    ],
  },
];

const formItemLayout = {
  labelCol: {
    xs: { span: 14 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 18 },
    sm: { span: 10 },
  },
};

export default function StoreManage() {
  const [spinning] = useState<boolean>(false); //loading
  const [list, setList] = useState<DataType[]>([]); //数据列表
  const [openAdd, setOpenAdd] = useState<boolean>(false); //门店框
  const [openEdit, setOpenEdit] = useState<boolean>(false); //编辑框
  const [selectCity, setCity] = useState<string>(""); //城市---展示地图位置
  const [BKey] = useState<string>("a62161c399cb9df9b76d4a1e3b9ae036"); //webKey
  const [lon, setLon] = useState<number>(116.397455); //经纬度  默认天安门
  const [lat, setLat] = useState<number>(39.909187); //经纬度
  const [form] = Form.useForm(); //添加表单
  const [form2] = Form.useForm(); //编辑表单
  const [openSetting, setOpenSetting] = useState<boolean>(false); //门店设置框
  const [subBtn, setSubBtn] = useState<boolean>(false); //提交按钮
  const [option] = useState([
    {
      value: "",
      label: "全部",
    },
    {
      value: "true",
      label: "开启中",
    },
    {
      value: "false",
      label: "未营业",
    },
  ]); //根据门店状态搜索
  const [searchName, setSearchName] = useState<string>(""); //搜索名称
  const [settingLon, setTingLon] = useState(0); //门店设置 ----服务范围
  const [settingLat, setTingLat] = useState(0); //门店设置 ----服务范围
  const [settingLon2, setTingLon2] = useState(0); //门店设置 ----还车范围
  const [settingLat2, setTingLat2] = useState(0); //门店设置 ----还车范围
  const [curID, setCurId] = useState(0); //修改门店服务范围

  // 名称搜索
  const onSearch = async (value: string) => {
    if (value !== "") {
      setSearchName(value);
      const { data } = await axios.get(
        "http://127.0.0.1:3100/zsl/getStoreList?name=" + searchName
      );
      if (data.code === 200) {
        setList(data.data);
      }
    } else {
      const { data } = await axios.get(
        "http://127.0.0.1:3100/zsl/getStoreList"
      );
      if (data.code === 200) {
        setList(data.data);
      }
    }
  };
  // 初次请求数据
  async function getList() {
    const { data } = await axios.get("http://127.0.0.1:3100/zsl/getStoreList");
    if (data.code === 200) {
      setList(data.data);
    }
  }

  //根据门店状态搜索
  const onChangeSelect = async (value: string) => {
    if (value === "") {
      const { data } = await axios.get(
        "http://127.0.0.1:3100/zsl/searchSelect"
      );
      if (data.code === 200) {
        setList(data.data);
      }
    } else {
      const { data } = await axios.get(
        "http://127.0.0.1:3100/zsl/searchSelect?status=" + value
      );
      if (data.code === 200) {
        setList(data.data);
      }
    }
  };

  useEffect(() => {
    getList();
  }, []);

  const columns: TableColumnsType<DataType> = [
    {
      title: "编号",
      width: 100,
      dataIndex: "id",
      key: "key",
    },
    {
      title: "名称",
      width: 100,
      dataIndex: "name",
      key: "name",
    },
    {
      title: "所在地",
      dataIndex: "address",
      key: "address",
      width: 150,
    },
    {
      title: "详细地址",
      dataIndex: "detailAds",
      key: "detailAds",
      width: 150,
    },
    {
      title: "负责人",
      dataIndex: "people",
      key: "people",
      width: 150,
    },
    {
      title: "联系电话",
      dataIndex: "tell",
      key: "tell",
      width: 150,
    },
    {
      title: "营业时间",
      dataIndex: "time",
      key: "time",
      width: 150,
    },
    {
      title: "门店状态",
      dataIndex: "status",
      key: "status",
      width: 150,
      render: (status) => {
        return (
          <>
            {status == "true" ? (
              <Tag color="green">营业中</Tag>
            ) : (
              <Tag color="red">未营业</Tag>
            )}
          </>
        );
      },
    },
    {
      title: "员工人数",
      dataIndex: "count",
      key: "count",
      width: 150,
    },
    {
      title: "车辆数",
      dataIndex: "carCount",
      key: "carCount",
      width: 100,
    },
    {
      title: "操作",
      key: "operation",
      width: 150,
      fixed: "right",
      render: (record) => {
        return (
          <div>
            <Button
              type="link"
              onClick={() => {
                editForm(record);
              }}
            >
              修改信息
            </Button>
            <Button type="link" onClick={() => editStoreSetting(record)}>
              门店设置
            </Button>
            <Popconfirm
              title="删除该条数据"
              description="是否要删除选中数据？"
              okText="Yes"
              cancelText="No"
              onConfirm={() => deleteStore(record.id)}
            >
              {" "}
              <Button type="link">删除门店</Button>
            </Popconfirm>
          </div>
        );
      },
    },
  ];
  // 地址转坐标
  const getLngLat = async (address: string) => {
    const { data } = await axios.get(
      `https://restapi.amap.com/v3/geocode/geo?address=${address}&key=${BKey}`
    );
    if (data.status == "1") {
      const curPoint = data.geocodes[0].location.split(",");
      setLon(curPoint[0]);
      setLat(curPoint[1]);
      console.log(curPoint, "地址转坐标");
    }
  };
  //城市选择
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const onChange = (value: any) => {
    setCity(value.join(""));
    //调用地址转坐标函数
    getLngLat(value.join(""));
  };

  //添加门店
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const onFinish = async (values: FormData) => {
    const obj = {
      name: values.name,
      address: values.address.join(""),
      detailAds: values.detailAds,
      people: values.people,
      tell: values.tell,
      time:
        moment(values.time[0]["$d"]).format("HH:mm") +
        "-" +
        moment(values.time[1]["$d"]).format("HH:mm"),
      lon: lon,
      lat: lat,
    };
    console.log(values);

    console.log(obj, "添加·········");

    const { data } = await axios.post(
      "http://127.0.0.1:3100/zsl/addStore",
      obj
    );
    if (data.code == 200) {
      message.success(data.msg);
    }
    setOpenAdd(false);
    // 重置表单
    form.resetFields();
  };

  // 修改门店
  const onEdit = async (values: FormData) => {
    console.log(values, "修改·········");
    const { data } = await axios.post(
      "http://127.0.0.1:3100/zsl/editStore",
      values
    );
    if (data.code === 200) {
      message.success(data.msg);
      setOpenEdit(false);
      getList();
    }
  };
  //表单修改/添加
  const editForm = (record?: DataType) => {
    if (record?.id) {
      console.log(record);
      setOpenEdit(true);
      form2.setFieldsValue(record);
    } else {
      setOpenAdd(true);
      setSubBtn(false);
      form.resetFields();
      console.log(record);
      console.log("添加");
    }
  };

  // 删除门店
  const deleteStore = async (id: number) => {
    const { data } = await axios.get(
      "http://127.0.0.1:3100/zsl/deleteStore?id=" + id
    );
    if (data.code === 200) {
      message.success(data.msg);
      getList();
    }
  };

  // 门店设置
  const editStoreSetting = (record: DataType) => {
    setCurId(record.id);
    // 门店服务
    setTingLon(Number(record.lon));
    setTingLat(Number(record.lat));
    // 还车范围
    setTingLon2(Number(record.setLon));
    setTingLat2(Number(record.setLat));
    setOpenSetting(true);
  };

  // 超出多少米
  const onChangeNumber = (value: number) => {
    console.log("changed", typeof value);
  };
  //收费
  const onChangePrice = (value: number) => {
    console.log("changed", typeof value);
  };
  // 关闭设置框
  const cloeseModel = () => {
    setOpenSetting(false);
    message.success("设置成功");
  };
  return (
    <div className="storeBigBox">
      <Spin spinning={spinning}>
        <Header title="门店管理" />
        <div className="searchBox">
          <div>
            <span
              style={{
                marginTop: "5px",
                display: "inline-block",
                marginRight: "5px",
              }}
            >
              门店名称
            </span>
            <Search
              placeholder="请输入内容"
              onSearch={onSearch}
              style={{
                width: 200,
              }}
            />
          </div>
          <div style={{ marginLeft: "50PX" }}>
            <span
              style={{
                marginTop: "5px",
                display: "inline-block",
                marginRight: "5px",
              }}
            >
              门店状态
            </span>
            <Select
              showSearch
              placeholder="请选择状态"
              optionFilterProp="children"
              onChange={onChangeSelect}
              filterOption={filterOption}
              options={option}
            />
          </div>
        </div>
        <div className="storeContent">
          <Button
            type="primary"
            style={{ float: "right", marginBottom: "10px" }}
            onClick={() => editForm()}
          >
            添加门店
          </Button>
          <Table
            columns={columns}
            dataSource={list}
            scroll={{ y: 350 }}
            pagination={{
              defaultPageSize: 3, //默认煤业显示条数
              defaultCurrent: 1, //默认当前页数第二页
              pageSizeOptions: ["3", "5", "10"], //每页显示多少条
              locale: {
                items_per_page: "条/页",
              },
            }}
          />
        </div>
        {/* 添加门店 */}
        <Modal
          title="添加门店"
          open={openAdd}
          footer={
            [] // 设置footer为空，去掉 取消 确定默认按钮
          }
          onCancel={() => setOpenAdd(false)}
        >
          <div className="formBox">
            <Form
              {...formItemLayout}
              form={form}
              name="stpre-add"
              onFinish={onFinish}
              style={{ maxWidth: 600 }}
            >
              <Form.Item
                name="name"
                label="门店名称"
                rules={[{ required: true, message: "请输入门店名称" }]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                name="address"
                label="所在地"
                rules={[{ required: true, message: "请输入所在地" }]}
              >
                <Cascader options={options} onChange={onChange} />
              </Form.Item>
              <Form.Item
                name="people"
                label="负责人"
                rules={[{ required: true, message: "请输入负责人" }]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                name="tell"
                label="联系电话"
                rules={[{ required: true, message: "请输入联系电话" }]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                name="time"
                label="营业时间"
                rules={[{ required: true, message: "请选择营业时间" }]}
              >
                <TimePicker.RangePicker />
              </Form.Item>
              <Form.Item name="detailAds" label="详细地址">
                <Input />
              </Form.Item>
              <Form.Item wrapperCol={{ span: 8, offset: 8 }}>
                <div
                  style={{ display: "flex", justifyContent: "space-around" }}
                >
                  {subBtn === false ? (
                    <Button type="primary" htmlType="submit">
                      添加
                    </Button>
                  ) : (
                    <Button type="primary" htmlType="submit">
                      修改
                    </Button>
                  )}
                  <Button type="primary" htmlType="reset">
                    重置
                  </Button>
                </div>
              </Form.Item>
            </Form>
            <Map lon={lon} lat={lat} selectCity={selectCity} />
          </div>
        </Modal>
        {/* 修改门店 */}
        <Modal
          title="修改门店"
          open={openEdit}
          footer={
            [] // 设置footer为空，去掉 取消 确定默认按钮
          }
          onCancel={() => setOpenEdit(false)}
        >
          <div className="formBox">
            <Form
              {...formItemLayout}
              form={form2}
              name="stpre-add"
              onFinish={onEdit}
              style={{ maxWidth: 600 }}
            >
              <Form.Item name="id" label="门店ID">
                <Input disabled />
              </Form.Item>
              <Form.Item
                name="name"
                label="门店名称"
                rules={[{ required: true, message: "请输入门店名称" }]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                name="address"
                label="所在地"
                rules={[{ required: true, message: "请输入所在地" }]}
              >
                <Cascader options={options} onChange={onChange} />
              </Form.Item>
              <Form.Item
                name="people"
                label="负责人"
                rules={[{ required: true, message: "请输入负责人" }]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                name="tell"
                label="联系电话"
                rules={[{ required: true, message: "请输入联系电话" }]}
              >
                <Input />
              </Form.Item>
              {/* <Form.Item name="time" label="营业时间">
                <TimePicker.RangePicker
                  // eslint-disable-next-line @typescript-eslint/no-explicit-any
                  onChange={(time: any) => selectTimer(time)}
                />
              </Form.Item> */}
              <Form.Item name="detailAds" label="详细地址">
                <Input />
              </Form.Item>
              <Form.Item wrapperCol={{ span: 8, offset: 8 }}>
                <div
                  style={{ display: "flex", justifyContent: "space-around" }}
                >
                  <Button type="primary" htmlType="submit">
                    修改
                  </Button>
                  <Button type="primary" htmlType="reset">
                    重置
                  </Button>
                </div>
              </Form.Item>
            </Form>
            <Map lon={lon} lat={lat} selectCity={selectCity} />
          </div>
        </Modal>
        {/* 门店设置 */}
        <Modal
          title="门店设置"
          open={openSetting}
          footer={
            [] // 设置footer为空，去掉 取消 确定默认按钮
          }
          onCancel={() => setOpenSetting(false)}
        >
          <div className="storeService">
            <p>1、门店服务范围</p>
            <div className="storeTop">
              <Maps lon={settingLon} lat={settingLat} id={curID} />
            </div>
            <p>1、取/还车收费范围</p>
            <div className="storeBtm">
              <MapTwo lon={settingLon2} lat={settingLat2} id={curID} />
            </div>
            <div style={{ width: "100%", display: "flex", marginTop: "10px" }}>
              <p style={{ marginRight: "5px" }}>收费范围 每超出</p>
              <InputNumber
                min={1}
                defaultValue={3}
                onChange={() => onChangeNumber}
              />
              <p style={{ marginLeft: "5px", marginRight: "5px" }}>收取费用</p>
              <InputNumber
                min={1}
                defaultValue={3}
                onChange={() => onChangePrice}
              />
              <p style={{ marginLeft: "5px", marginRight: "5px" }}>元</p>
            </div>
            <div
              style={{
                textAlign: "center",
                marginTop: "20px",
              }}
            >
              <Button type="dashed" onClick={() => setOpenSetting(false)}>
                取消
              </Button>
              <Button
                type="primary"
                style={{ marginLeft: "10px" }}
                onClick={cloeseModel}
              >
                保存
              </Button>
            </div>
          </div>
        </Modal>
      </Spin>
    </div>
  );
}
